from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from rest_framework.permissions import IsAdminUser
from apps.history.models import Department
from apps.enroll.models import EmailVerifyRecord, NewMember
from apps.enroll.serializers import DepartmentSerializer, NewMemberSerializer, NewMemberScheduleSerializer, \
    SendEmailSerializer
from rest_framework import status
from rest_framework.views import APIView
from apps.enroll.email import send_code_email
from django.views.decorators.csrf import csrf_exempt
from django.shortcuts import HttpResponse
from ITShowPlatform.settings import BASE_DIR
from apps.enroll.models import NewMember
from utils.util import get_msg
import re,configparser,os
import time
import xlwt

conf = configparser.RawConfigParser()

conf.read(os.path.join(BASE_DIR, "config.ini"), encoding="utf-8")


class DepartmentMessageView(GenericAPIView):
    """获取部门信息"""
    global queryset
    queryset = Department.objects.filter(status=True)
    serializer_class = DepartmentSerializer

    def get(self, request):
        # serializer = self.get_serializer(instance=self.get_queryset(), many=True)  #会自动补完成绝对路径
        serializer = DepartmentSerializer(instance=queryset,many=True)
        if request.query_params:
            return Response({"code": 40000, "msg": get_msg("40000")})
        for i in serializer.data:
            i["icon"] = (conf.get("Django","Host") + i["icon"])
        return Response({"code": 20000, "msg": get_msg("20000"), "data": serializer.data})


class SignUpView(GenericAPIView):
    """
    新成员报名
    post:提交新学员信息
    get:根据邮箱及手机号获取成员录取状态
    """

    serializer_class = NewMemberSerializer
    queryset = NewMember.objects.all()

    @csrf_exempt
    def post(self, request):
        data = request.data
        print(data)
        serializer = self.get_serializer(data=data)
        code = data['verification_code']
        ret = serializer.is_valid(raise_exception=False)
        if ret:
            # print(f"code={code}")
            try:
                oj = EmailVerifyRecord.objects.get(email=data['email'])
                print(oj.code,code)
                send_time = str(oj.send_time).split('+')[0].split('.')[0]
                send_time = time.mktime(time.strptime(send_time, '%Y-%m-%d %X'))
                now = time.time()
                if now - send_time > 120:
                    oj.delete()
                    return Response(
                        {"code": 40000, "msg": get_msg("45032")},
                        status=status.HTTP_400_BAD_REQUEST)
                if str(code) != oj.code:
                    return Response({"code": 45031, "msg": get_msg("44031")},
                                    status=status.HTTP_400_BAD_REQUEST)
            except (EmailVerifyRecord.DoesNotExist,Exception):
                return Response({"code": 44032, "msg": get_msg("44032")},
                                status=status.HTTP_400_BAD_REQUEST)
            
            serializer.save()
            oj.delete()
            return Response({"code": 20000, "msg": get_msg(20000)})
        else:
            error = {}
            for (i, j) in zip(serializer.errors.keys(), serializer.errors.values()):
                error[str(i)] = str(j[0])
                return Response({"code": int(j[0]), "msg": get_msg(j[0])}, status=status.HTTP_400_BAD_REQUEST)
            #return Response({"code": 40000, "msg": error}, status=status.HTTP_400_BAD_REQUEST)

    def get(self, request):
        string = request.query_params.get('string', '')
        try:
            if re.match('^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$', string):
                queryset = self.get_queryset().get(email=string)
            elif re.match('^(13[0-9]|14[5|7]|15[0|1|2|3|4|5|6|7|8|9]|18[0|1|2|3|5|6|7|8|9]|17[0-9]|19[0-9])\d{8}$', string):
                queryset = self.get_queryset().get(phone_number=string)
            else:
                queryset = self.get_queryset().get(id=-1)
        except NewMember.DoesNotExist:
            return Response({"code": 40000, "msg": get_msg(45030)})
        serializer = NewMemberScheduleSerializer(instance=queryset)

        return Response({"code": 20000, "msg": get_msg(20000), "data": serializer.data})


class SendEmailView(APIView):
    """发送邮件"""

    @csrf_exempt
    def post(self, request):
        data = request.data
        serializer = SendEmailSerializer(data=data)
        
        # code_serializer = Code_email_serializer()
        ret = serializer.is_valid()
        if ret:
            # serializer.save()
            if not send_code_email(data.get("email")):
                return Response({"code": 42031, "msg": get_msg(42031)}, status=status.HTTP_400_BAD_REQUEST)
            return Response({"code": 20000, "msg": get_msg(20000)})
        else:
            error = {}
            for (i, j) in zip(serializer.errors.keys(), serializer.errors.values()):
                error[str(i)] = str(j[0])
                
                return Response({"code": int(j[0]), "msg": get_msg(j[0])}, status=status.HTTP_400_BAD_REQUEST)
            #return Response({"code": 40000, "msg": error}, status=status.HTTP_400_BAD_REQUEST)


class OucView(APIView):
    """用来给ipad自动任务跑每日上报脚本的，装杯用"""

    def get(self, request):
        return Response({"code": 20000, "msg": get_msg(20000)})



class ExportView(APIView):
    #permission_classes = [IsAdminUser]
    """
    不会带token访问，准备交给run宁哥
    """
    
    def get(self, request, *args, **kwargs):
        response = HttpResponse(content_type='application/ms-excel')
        # 设置文件名称
        response['Content-Disposition'] = 'attachment; filename="NewMember.xls"'
        # 创建工作簿
        wb = xlwt.Workbook(encoding='utf-8')
        # 创建表
        ws = wb.add_sheet('Member')
        row_num = 0
        font_style = xlwt.XFStyle()
        # 二进制
        font_style.font.bold = True
        # 表头内容
        columns = ['ID', '姓名', '性别', '年级专业',"意向部门","手机号码","邮箱","期待的话","报名状态"]
        # 写进表头内容
        for col_num in range(len(columns)):
            ws.write(row_num, col_num, columns[col_num], font_style)
        # Sheet body, remaining rows
        font_style = xlwt.XFStyle()
        # 获取数据库数据
        rows = NewMember.objects.values_list('id', "name","sex","major","department","phone_number","email","expectation","status")
        # 遍历提取出来的内容
        for row in rows:
            row_num += 1
            # 逐行写入Excel

            for col_num in range(len(row)):
                #return HttpResponse(col_num)
                ws.write(row_num, col_num, row[col_num], font_style)

        wb.save(response)
        return response

#test
